/**
 * @Description: 高德离线地图
 * @Author: xubaoliang
 * @Date: 2022-01-25 09:19:27
 */
import TileLayer from "ol/layer/Tile";
import {XYZ} from "ol/source";
import {Map, View} from "ol";

let AMap = {
  /**
   * 初始化百度地图
   * @param elId
   * @param configs
   * @param options
   * @return {Map}
   */
  init: function (elId, configs, options) {
    let tileUrl = "";
    if(configs.mapType.toLowerCase() === 'amap') {
      tileUrl = process.env.VUE_APP_MAP_TILE + "/{z}/{x}/{y}.png";
    }
    else {
      tileUrl = "https://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}";
    }
    let mapLayer = new TileLayer({
      id: 'baseLayer',
      source: new XYZ({
        url: tileUrl,
        crossOrigin: 'anonymous',
      })
    });

    let mapApp = new Map({
      target: elId,
      layers: [mapLayer],
      view: new View({
        projection: "EPSG:4326",    //使用这个坐标系
        center: options.center || configs.mapCenter,
        zoom: options.zoom || configs.defaultZoom,
        minZoom: options.minZoom || configs.minZoom,
        maxZoom: options.maxZoom || configs.maxZoom,
        // 设置缩放级别为整数
        constrainResolution: true,
        // 关闭无级别缩放地图
        smoothResolutionConstraint: false
      }),
      controls: []
    });
    return mapApp;
  },
  /**
   * 实时路况
   * @return {string|TileLayer<TileSourceType>}
   */
  addTrafficLayer() {
    return new TileLayer({
      id: 'trafficLayer',
      source: new XYZ({
        params: {
          refresh: Date.now()
        },
        //crossOrigin: 'anonymous',
        tileUrlFunction(tileCoord) {
          let z = 17 - tileCoord[0] > 0 ? 17 - tileCoord[0] : 1;
          let x = tileCoord[1];
          let y = tileCoord[2];
          return `https://tm.amap.com/trafficengine/mapabc/traffictile?v=1.0&t=1&zoom=${z}&x=${x}&y=${y}&hash=${Math.random()}`;
        }
      })
    });
  },
  /**
   * 实时路况预测
   * @param day
   * @param hour
   * @param minutes
   * @return {string|TileLayer<TileSourceType>}
   */
  addHistoryTrafficLayer(day, hour, minutes) {
    if(!day) {
      day = 1;
    }
    if(!hour) {
      hour = 10;
    }
    if(!minutes) {
      minutes = 0;
    }
    return new TileLayer({
      id: 'historyTrafficLayer',
      source: new XYZ({
        params: {
          refresh: new Date().getTime()
        },
        //crossOrigin: 'anonymous',
        tileUrlFunction(tileCoord) {
          let z = tileCoord[0];
          let x = tileCoord[1];
          let y = tileCoord[2];
          return `https://history.traffic.amap.com/traffic?type=2&day=${day}&hh=${hour}&mm=${minutes}&x=${x}&y=${y}&z=${z}`;
        }
      })
    });
  }
}

export default AMap;
